﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office;
using System.Data;
using System.IO;

namespace Pub
{
    public class CWord
    {

        public const int I_TYP_TXT = 1;         //文本
        public const int I_TYP_PIC = 2;         //图片
        public const int I_TYP_TAB = 3;         //表格

        public string temDocName;
        public string newDocName;

        public Word._Document wordDoc2;
        public object Nothing = System.Reflection.Missing.Value;
        public object format = Word.WdSaveFormat.wdFormatDocument;
        public Word._Application wordApp;
        public object srcFileName;

        public struct BOOK
        {
            public int bookLength;
            public string bookText;
        }


        public List<WDoc> wd_Lst = new List<WDoc>();

        public struct WDoc
        {
            public int i_Typ;

            public string bookmarkName;
            public string Text;
            public string picFullName;
            public string picPath;
            public string picName;
            public DataTable dt;
        }

        public void addVal(string bookMarkName, string s_val)
        {
            WDoc wd = new WDoc();
            wd.bookmarkName = bookMarkName;
            wd.i_Typ = I_TYP_TXT;
            wd.Text = s_val;
            wd_Lst.Add(wd);
        }


        public void addVal(string bookMarkName, int i_typ, object o_val)
        {
            WDoc wd = new WDoc();
            wd.bookmarkName = bookMarkName;
            wd.i_Typ = i_typ;
            if (i_typ == I_TYP_TXT)
            {
                wd.Text = (string)o_val;
            }
            if (i_typ == I_TYP_PIC)
            {
                wd.picFullName = (string)o_val;
            }
            if (i_typ == I_TYP_TAB)
            {
                wd.dt = (DataTable)o_val;
            }

            wd_Lst.Add(wd);
        }

        public void saveAs(string newDocName)
        {
            saveAs(null, newDocName);
        }

        public void saveAs(string temDocName, string newDocName)
        {
            CDebug.EnterMethod("制作word产品");

            if (temDocName != string.Empty)
            {
                this.temDocName = temDocName;
            }
            this.newDocName = newDocName;
            File.Copy(temDocName, newDocName);

            //object Nothing = System.Reflection.Missing.Value;
            //object format = Word.WdSaveFormat.wdFormatDocument;
            //Word._Application wordApp = new Word.ApplicationClass();
            //打开模版
            //object srcFileName = temDocName;
            if (wordDoc2 == null)
            {
                OpenWordDot(this.newDocName);
            }


            try
            {

                //替换书签
                CDebug.Send("书签个数：" + wd_Lst.Count);
                for (int i = 0; i < wd_Lst.Count; i++)
                {
                    try
                    {
                        object bookmarkName = wd_Lst[i].bookmarkName;
                        string sVal = "";

                        //判断书签是否存在
                        if (!wordDoc2.Bookmarks.Exists(wd_Lst[i].bookmarkName))
                        {
                            CDebug.Send("书签不存在: index=" + i + ", name=" + wd_Lst[i].bookmarkName);
                            continue;
                        }

                        wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select();

                        if (wd_Lst[i].i_Typ == I_TYP_TXT)     //填充文本
                        {
                            sVal = "[文本]" + wd_Lst[i].Text;
                            wordDoc2.Bookmarks.get_Item(ref bookmarkName).Range.Text = wd_Lst[i].Text;

                        }

                        if (wd_Lst[i].i_Typ == I_TYP_PIC)     //填充图片
                        {
                            sVal = "[图片]" + wd_Lst[i].picFullName;
                            wordApp.Selection.InlineShapes.AddPicture(wd_Lst[i].picFullName,
                                ref Nothing, ref Nothing, ref Nothing);

                        }

                        if (wd_Lst[i].i_Typ == I_TYP_TAB)
                        {
                        }

                        CDebug.Send("填充书签: index=" + i + ", name=" + wd_Lst[i].bookmarkName + ", value=" + sVal);
                    }
                    catch (System.Exception ex2)
                    {
                        CDebug.SendError(ex2.ToString());
                        CDebug.Send("填充书签出错", ex2);
                    }

                }


                wordDoc2.Save();
                //object sFileName = newDocName;
                //wordDoc2.SaveAs(ref sFileName,
                //    ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                //    ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            }
            catch (Exception ex)
            {
                CDebug.SendError(ex.ToString());
                CDebug.Send("填充word出错", ex);
            }
            finally
            {
                try
                {
                    //关闭网页wordDoc2
                    wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing);
                    if (wordDoc2 != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);
                        wordDoc2 = null;
                    }

                    //关闭wordApp
                    wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
                    if (wordApp != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                        wordApp = null;
                    }

                    CDebug.ExitMethod("制作word产品");
                }
                catch
                {
                }
            }


        }

        public string getBmVal(string sBook)
        {

            string str = "";

            //System.Collections.IEnumerator enu = wordApp.ActiveDocument.Bookmarks.GetEnumerator();

            try
            {
                object bookmarkName = sBook;
                if (wordDoc2.Bookmarks.Exists(sBook))
                {
                    wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select();

                    str = wordDoc2.Bookmarks.get_Item(ref bookmarkName).Range.Text;
                }
                else
                {
                    CDebug.Send("书签不存在: " + sBook);
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError("读取书签出错: " + sBook + "; " + ex.ToString());
                CDebug.Send("读取书签出错", ex);
            }

            //GC.Collect();

            return str;
        }

        public void getBookLst(string temDocName, ref List<BOOK> bookM)
        {
            CDebug.EnterMethod("读取书签");
            FileInfo finf = new FileInfo(temDocName);

            string newFile = finf.Directory.FullName + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".DOC";

            CDebug.Send("临时文件名称：" + newFile);
            File.Copy(temDocName, newFile);

            OpenWordDot(newFile);

            //读取文档书签
            bookM.Clear();
            int k = 1;
            string sBookVal = getBmVal("b1");
            while (sBookVal != string.Empty)
            {
                int j = 1;
                while (sBookVal.IndexOf("{" + k + "_" + j + "}") != -1)
                {
                    j++;
                }

                CWord.BOOK b1 = new CWord.BOOK();
                b1.bookLength = j--;
                b1.bookText = sBookVal;
                bookM.Add(b1);
                //CDebug.Send("i=" + k + ",j=" + j + ": " + sBookVal); //sBookVal.Substring(0, sBookVal.Length > 50 ? 50 : sBookVal.Length));

                k++;
                sBookVal = getBmVal("b" + k);
            }

            /*
            CDebug.EnterMethod("书签个数: " + wordDoc2.Bookmarks.Count);
            System.Collections.IEnumerator enu = wordDoc2.Bookmarks.GetEnumerator();
            Microsoft.Office.Interop.Word.Bookmark bk = null;
            for (int i = 0; i < wordDoc2.Bookmarks.Count; i++)
            {
                enu.MoveNext();

                bk = (Microsoft.Office.Interop.Word.Bookmark)enu.Current;

                string bookName = bk.Name.ToString();
                string bookVal = bk.Range.Text;
                CDebug.Send(bookName + "=" + bookVal);
            }
            CDebug.ExitMethod("列举书签");
            */

            CDebug.Send("通用书签个数:" + bookM.Count);

            CloseWordDot();

            File.Delete(newFile);

            CDebug.ExitMethod("读取书签");
        }

        public string getBookVal(string temDocName, string bookM)
        {
            CDebug.EnterMethod("读取书签");
            FileInfo finf = new FileInfo(temDocName);

            string newFile = finf.Directory.FullName + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".DOC";

            CDebug.Send("临时文件名称：" + newFile);
            File.Copy(temDocName, newFile);

            OpenWordDot(newFile);

            //读取文档书签

            string sBookVal = getBmVal(bookM);


            CloseWordDot();

            File.Delete(newFile);

            CDebug.ExitMethod("读取书签");

            return sBookVal;
        }


        public void OpenWordDot(string temDocName)
        {
            if (wordDoc2 == null)
            {
                CDebug.Send("打开文档：" + temDocName);
                this.temDocName = temDocName;
                //打开模版
                //object Nothing = System.Reflection.Missing.Value;
                //object format = Word.WdSaveFormat.wdFormatDocument;
                wordApp = new Word.ApplicationClass();
                srcFileName = temDocName;
                wordDoc2 =
                    wordApp.Documents.Open(ref srcFileName, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                    ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                    ref Nothing, ref Nothing);
            }
        }

        public void CloseWordDot()
        {
            try
            {
                if (wordDoc2 == null) return;

                CDebug.Send("关闭文档：" + this.temDocName);
                object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                //关闭网页wordDoc2
                wordDoc2.Close(ref saveOption, ref Nothing, ref Nothing);
                if (wordDoc2 != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);
                    wordDoc2 = null;
                }

                //关闭wordApp
                wordApp.Quit(ref saveOption, ref Nothing, ref Nothing);
                if (wordApp != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                    wordApp = null;
                }

            }
            catch (Exception ex)
            {
                CDebug.SendError(ex.ToString());
                CDebug.Send("关闭word出错", ex);
            }
        }

        /*
        //打开word
        private void OpenWordDoc(string FileName, ref Microsoft.Office.Interop.Word.Document wDoc, ref  Microsoft.Office.Interop.Word.Application WApp)
        {
            if (FileName == "") return;
            Microsoft.Office.Interop.Word.Document thisDocument = null;
            Microsoft.Office.Interop.Word.FormFields formFields = null;
            Microsoft.Office.Interop.Word.Application thisApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            thisApplication.Visible = true;
            thisApplication.Caption = "";
            thisApplication.Options.CheckSpellingAsYouType = false;
            thisApplication.Options.CheckGrammarAsYouType = false;

            Object filename = FileName;
            Object ConfirmConversions = false;
            Object ReadOnly = true;
            Object AddToRecentFiles = false;

            Object PasswordDocument = System.Type.Missing;
            Object PasswordTemplate = System.Type.Missing;
            Object Revert = System.Type.Missing;
            Object WritePasswordDocument = System.Type.Missing;
            Object WritePasswordTemplate = System.Type.Missing;
            Object Format = System.Type.Missing;
            Object Encoding = System.Type.Missing;
            Object Visible = System.Type.Missing;
            Object OpenAndRepair = System.Type.Missing;
            Object DocumentDirection = System.Type.Missing;
            Object NoEncodingDialog = System.Type.Missing;
            Object XMLTransform = System.Type.Missing;

            try
            {
                Microsoft.Office.Interop.Word.Document wordDoc =
                thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
                ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
                ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
                ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
                ref NoEncodingDialog, ref XMLTransform);

                thisDocument = wordDoc;
                wDoc = wordDoc;
                WApp = thisApplication;
                formFields = wordDoc.FormFields;
            }
            catch (Exception ex)
            {

            }

        }



        //获取标签数据
        public string GetDocumentBookmarkData(string FileName)
        {

            Microsoft.Office.Interop.Word.Document wDoc = null;
            Microsoft.Office.Interop.Word.Application wApp = null;
            this.OpenWordDoc(FileName, ref wDoc, ref wApp);
            object oEndOfDoc = "\\endofdoc";
            object missing = System.Reflection.Missing.Value;

            string str = "";

            System.Collections.IEnumerator enu = wApp.ActiveDocument.Bookmarks.GetEnumerator();

            while (enu.MoveNext())
            {
                Microsoft.Office.Interop.Word.Bookmark bk = (Microsoft.Office.Interop.Word.Bookmark)enu.Current;

                str += "{" + bk.Name.ToString() + ":" + bk.Range.Text + "}";
            }

            object o = null;

            wDoc.Close(ref missing, ref missing, ref missing);
            wApp.Quit(ref missing, ref missing, ref missing);

            if (wDoc != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
                wDoc = null;
            }

            if (wApp != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
                wApp = null;
            }

            GC.Collect();

            return str;
        }


        //设定标签的数据
        
        public string SetDocumentBookmarkData(string FileName, System.Data.DataTable dt)
        {
            //打开文档
            Microsoft.Office.Interop.Word.Document wDoc = null;
            Microsoft.Office.Interop.Word.Application wApp = null;
            this.OpenWordDoc(FileName, ref wDoc, ref wApp);
            object oEndOfDoc = "\\endofdoc";
            object missing = System.Reflection.Missing.Value;

            //设定标签数据
            System.Collections.IEnumerator enu = wApp.ActiveDocument.Bookmarks.GetEnumerator();

            string[] strbook = new string[dt.Columns.Count - 1];
            int i = 0;
            Microsoft.Office.Interop.Word.Bookmark bk = null;
            while (enu.MoveNext())
            {
                bk = (Microsoft.Office.Interop.Word.Bookmark)enu.Current;

                if (bk.Name.ToString().Trim() != "Table")
                {
                    strbook = bk.Name.ToString();
                    i++;
                }
            }

            object tempobject = null;
            int length = 0;
            for (i = 0; i < strbook.Length; i++)
            {
                tempobject = strbook.ToString();

                if (wApp.ActiveDocument.Bookmarks.Exists(strbook.ToString()))
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref tempobject).Select();

                    wApp.Selection.Text = dt.Rows[0][strbook].ToString();

                    length = dt.Rows[0][strbook].ToString().Length;
                    wApp.ActiveDocument.Bookmarks.get_Item(ref tempobject).End = wApp.ActiveDocument.Bookmarks.get_Item(ref tempobject).End + length;
                }

            }

            InsertTabletoBookmark("Table", ref wDoc, ref wApp);


            //收尾工作
            object o = null;

            string guid = System.Guid.NewGuid().ToString();
            object sFileName = "D:/Test/office/word/" + guid + ".doc";

            if (wDoc.SaveFormat == (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument)
            {
                wDoc.Application.ActiveDocument.SaveAs(ref sFileName, ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing,
                ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
            }

            wDoc.Close(ref missing, ref missing, ref missing);
            wApp.Quit(ref missing, ref missing, ref missing);

            if (wDoc != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
                wDoc = null;
            }

            if (wApp != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
                wApp = null;
            }

            GC.Collect();

            return guid + ".doc";
        }
        

        //插入表格数据
        private bool InsertTabletoBookmark(string objTable, ref Microsoft.Office.Interop.Word.Document wDoc, ref  Microsoft.Office.Interop.Word.Application WApp)
        {
            object oEndOfDoc = "\\endofdoc";
            object missing = System.Reflection.Missing.Value;

            object objBookmark = objTable;

            WApp.ActiveDocument.Bookmarks.get_Item(ref objBookmark).Select();

            Microsoft.Office.Interop.Word.Table table = wDoc.Tables.Add(WApp.Selection.Range, 3, 4, ref missing, ref missing);
            table.Cell(1, 1).Range.Text = "表：" + WApp.ActiveDocument.Bookmarks.get_Item(ref objBookmark).Range.Tables[1].Rows.Count;

            return true;
        }


        */


        /// <summary>
        /// word转为txt
        /// </summary>
        /// <param name="docName"></param>
        /// <param name="txtName"></param>
        public void wordToTxt(string docName, string txtName)
        {
            Word._Application app = new Word.ApplicationClass();
            app.Visible = false;
            string strFile = docName;
            object obj = System.Reflection.Missing.Value;
            Object infile = (object)strFile;
            Word._Document doc = app.Documents.Open(ref infile, ref obj, ref obj, ref obj, ref obj,
                ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj);

            string strnew = txtName; //"c:\\bbb.txt";
            Object outfile = (object)strnew;
            //Object fmt = (object)Word.WdSaveFormat.wdFormatText;
            Object fmt = (object)Word.WdSaveFormat.wdFormatEncodedText;

            List<string> list = new List<string>();
            // GetDataObject检索当前剪贴板上的数据
            System.Windows.Forms.IDataObject iData = Clipboard.GetDataObject();

            doc.SaveAs(ref outfile, ref fmt, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj);

            doc.Close(ref obj, ref obj, ref obj);
            app.Quit(ref obj, ref obj, ref obj);
            app = null;

        }


        public string DefValCls(string sText)
        {
            try
            {
                //将数据空位替换为数据
                int k_break = 0;
                string stem1 = CPub.findStrBetween(sText, "[", "]");
                while (stem1 != string.Empty)
                {
                    //CDebug.Send(stem1);
                    sText = sText.Replace("[" + stem1 + "]", "");
                    stem1 = CPub.findStrBetween(sText, "[", "]");
                    k_break++;
                    if (k_break > 1000) break;
                }


            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
                CDebug.Send("替换标记时出错", ex);
            }
            return sText;
        }

    }
}
